package com.google.project.client.Director;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.project.client.Service.LoginService;
import com.google.project.client.Service.LoginServiceAsync;
import com.google.project.client.Service.ProjectReportService;
import com.google.project.client.Service.ProjectReportServiceAsync;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.client.Service.UsersService;
import com.google.project.client.Service.UsersServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.ProjectReportDTO;
import com.google.project.shared.UsersDTO;

public class DRTProjectReportList extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField(provided = true)
	CellTable<ProjectReportDTO> ctbProjectReport = new CellTable<ProjectReportDTO>();
	@UiField
	SimplePager pager;
	@UiField
	ListBox cbPm;
	@UiField
	ListBox cbProject;
	@UiField
	Button btnSearch;
	@UiField
	ListBox cbStatus;

	interface Binder extends UiBinder<Widget, DRTProjectReportList> {
	}

	private final ProjectServiceAsync projService = GWT
			.create(ProjectService.class);
	private final LoginServiceAsync loginService = GWT
			.create(LoginService.class);
	private final ProjectReportServiceAsync projectReportSv = GWT
			.create(ProjectReportService.class);
	private final UsersServiceAsync userSv = GWT.create(UsersService.class);
	private List<ProjectReportDTO> listReportDTO = new ArrayList<ProjectReportDTO>();

	UsersDTO currUser = new UsersDTO();

	public DRTProjectReportList() {
		initWidget(binder.createAndBindUi(this));
		fillCbStatus();
		fillCombobox();
		initTable();
		getUserInfo();
	}

	/***
	 * Fix data to cbStatus
	 */
	public void fillCbStatus() {
		cbStatus.addItem("---Tất cả---", "-1");
		cbStatus.addItem("Chưa đọc", "1");
		cbStatus.addItem("Đã đọc", "0");
		cbStatus.setSelectedIndex(1);
	}

	/***
	 * Fill data to cbProject
	 */
	public void fillCbProject(final String _userId) {
		try {
			projService.getProjectList(new AsyncCallback<List<ProjectDTO>>() {

				@Override
				public void onFailure(Throwable caught) {

				}

				@Override
				public void onSuccess(List<ProjectDTO> result) {

					if (result != null && result.size() > 0) {

						for (ProjectDTO proj : result) {
							if (!_userId.equalsIgnoreCase("") && _userId!=null) {
								if (proj.getUserId().equals(_userId)) {
									cbProject.addItem(proj.getProjectName(),
											proj.getProjectID());
								}
							}
							else if(_userId.equalsIgnoreCase("") || _userId==null){
								cbProject.addItem(proj.getProjectName(),
										proj.getProjectID());
							}
						}

					}

				}
			});
		} catch (Exception ex) {
			ex.getMessage();
		}

	}

	// fill combobox :pm && project
	public void fillCombobox() {
		try {
			cbPm.addItem("---Tất cả---", "-1");
			cbProject.addItem("---Tất cả---", "-1");
			userSv.getUserList(new AsyncCallback<List<UsersDTO>>() {

				@Override
				public void onFailure(Throwable caught) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onSuccess(List<UsersDTO> result) {
					for (UsersDTO usersDTO : result) {
						if (usersDTO.getUserGroup()!=null && usersDTO.getUserGroup() == 2) {
							String display = usersDTO.getUserName() + " ("
									+ usersDTO.getFullName() + ")";
							cbPm.addItem(display, usersDTO.getUserId());
							fillCbProject(usersDTO.getUserId());
						}
					}

				}
			});
		} catch (Exception ex) {
			ex.getMessage();
		}
	}

	// get userID from session + load data khi moi vao
	public void getUserInfo() {
		loginService.getCurrentUserDTO(new AsyncCallback<UsersDTO>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(UsersDTO result) {

				currUser = result;
				getReportByDR(currUser.getUserId());
			}

		});
	}

	// getAll dailyReport where drId + statusOfReport=1-chưa đọc
	public void getReportByDR(String _userID) {
		projectReportSv.getAllProjectReport(
				new AsyncCallback<List<ProjectReportDTO>>() {

					@Override
					public void onFailure(Throwable caught) {
						Window.alert("Có lỗi xảy ra!");
					}

					@Override
					public void onSuccess(List<ProjectReportDTO> result) {
						listReportDTO=result; //lấy về tất cả báo cáo dự án
						List<ProjectReportDTO> list=new ArrayList<ProjectReportDTO>();
						for (ProjectReportDTO projectReportDTO : result) {
							if(projectReportDTO.getStatus()==1){ //báo cáo mới
								list.add(projectReportDTO);
							}
						}
						LoadData(list);
					}
				});
	}


	// init ctbDailyReport
	public void initTable() {
		TextColumn<ProjectReportDTO> index = new TextColumn<ProjectReportDTO>() {
			@Override
			public String getValue(ProjectReportDTO object) {
				return object.getIndex()+"";
			}
		};
		Column<ProjectReportDTO, String> projectColumn = new Column<ProjectReportDTO, String>(
				new ClickableTextCell()) {
			@Override
			public String getValue(ProjectReportDTO object) {
				return object.getProjectDTO().getProjectName();
			}
		};
		projectColumn
		.setFieldUpdater(new FieldUpdater<ProjectReportDTO, String>() {

			@Override
			public void update(int index,
					ProjectReportDTO projectReportDTO, String value) {
				if( Integer.parseInt((cbStatus.getValue(cbStatus.getSelectedIndex())))==1){
					int status = 0;
					projectReportSv.updateStatusProjectReport(
							projectReportDTO.getId(), status,
							new AsyncCallback<Void>() {

								@Override
								public void onFailure(Throwable caught) {
									Window.alert("Có lỗi xảy ra!");

								}

								@Override
								public void onSuccess(Void result) {

								}
							});
				}
				
				 DRTEntrypoint.get().DRTProjectReportDetail(projectReportDTO);
			}
		});
		// Tên Người gửi
		TextColumn<ProjectReportDTO> userReport = new TextColumn<ProjectReportDTO>() {
			@Override
			public String getValue(ProjectReportDTO object) {
				return object.getFromUserName();
			}
		};
		// Ngày báo cáo
		TextColumn<ProjectReportDTO> createdOnDate = new TextColumn<ProjectReportDTO>() {
			@Override
			public String getValue(ProjectReportDTO object) {
				return CommonFuntion.convertToDate(new Date(object
						.getCreatedOnDate()));
			}
		};
		projectColumn.setCellStyleNames("celltable");
		ctbProjectReport.addColumn(index, "STT");
		ctbProjectReport.addColumn(projectColumn, "Dự án");
		ctbProjectReport.addColumn(createdOnDate, "Báo cáo ngày");
		ctbProjectReport.addColumn(userReport, "Người báo cáo");
		ctbProjectReport.setStyleName("ttable");

	}

	// load data to celltable
	protected void LoadData(List<ProjectReportDTO> projectReportList) {

		ListDataProvider<ProjectReportDTO> dataProvider = new ListDataProvider<ProjectReportDTO>();

		// Connect the table to the data provider.
		dataProvider.addDataDisplay(ctbProjectReport);

		// Add the data to the data provider, which automatically pushes it to
		// the widget
		int index=1;
		List<ProjectReportDTO> list = dataProvider.getList();
		for (ProjectReportDTO projectReport : projectReportList) {
			projectReport.setIndex(index);
			list.add(projectReport);
			index++;
		}
		// SimplePager
		pager.setDisplay(ctbProjectReport);
		pager.setPage(5);
	}

	// Hàm search
	@UiHandler("btnSearch")
	void onBtnSearchClick(ClickEvent event) {
		Boolean condition = true;
		List<ProjectReportDTO> Templist = new ArrayList<ProjectReportDTO>();
		if (listReportDTO.size() > 0) {
			for (ProjectReportDTO projectReportDTO : listReportDTO) {
				if (!cbProject.getValue(cbProject.getSelectedIndex()).equals(
						"-1")) {
					String projectID = cbProject.getValue(cbProject
							.getSelectedIndex());
					condition = condition
							&& (projectReportDTO.getProjectId().equals(projectID));

				}
				if (!cbPm.getValue(cbPm.getSelectedIndex()).equals("-1")) {
					String pmID = cbPm.getValue(cbPm.getSelectedIndex());
					condition = condition
							&& (projectReportDTO.getFromUserID()
									.equals(pmID));

				}
				if (!cbStatus.getValue(cbStatus.getSelectedIndex())
						.equals("-1")) {
					int status = Integer.parseInt(cbStatus.getValue(cbStatus
							.getSelectedIndex()));
					if (status == 0) {
						condition = condition
								&& ((projectReportDTO.getStatus() == 0) || (projectReportDTO
										.getStatus() == 2));
					} else if (status == 1) {
						condition = condition
								&& ((projectReportDTO.getStatus() == 1));
					}

				}
				if (condition) {
					Templist.add(projectReportDTO);
				}
				condition = true;
			}
		}
		LoadData(Templist);
	}

	// onChange
	@UiHandler("cbPm")
	void onCbPmChange(ChangeEvent event) {
		if (cbPm.getValue(cbPm.getSelectedIndex()) != null) {
			cbProject.clear();
			String value=cbPm.getValue(cbPm.getSelectedIndex());
			if(!value.equalsIgnoreCase("-1")){
				cbProject.addItem("---Lựa chọn---", "-1");
				fillCbProject(value);
			}else{
				cbProject.addItem("---Tất cả---", "-1");
				fillCbProject("");
			}
		}
	}
}
